const Service = require('./index')
const userModel = require('@/models/user.model')

class UserService extends Service {
  /**
   * 用户分页查询
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} articleTitle
   * @param {*} status
   * @param {*} nickname
   */
  async findPage (pageNo = 1, pageSize = 20, {
    status,
    searchKeywords,
    nickname,
    email,
    tel,
    username,
    startTime,
    endTime
  }) {
    try {
      const { list, total } = await userModel.findPage({
        pageNo,
        pageSize,
        andConditions: {
          equal: {
            'user.status': status
          },
          like: {
            'user.username': username,
            'user.nickname': nickname,
            'user.email': email,
            'user.tel': tel
          }
        },
        orConditions: {
          like: {
            'user.nickname': searchKeywords,
            'user.email': searchKeywords,
            'user.tel': searchKeywords
          }
        },
        betweenConditions: {
          'user.createTime': [startTime, endTime]
        }
      })
      return this.skipPage(list.map(item => {
        return {
          ...item,
          bindwx: Boolean(item.openid),
          bindPassword: Boolean(Number(item.bindPassword)),
          password: undefined,
          openid: undefined,
          sessionKey: undefined
        }
      }), total, pageNo, pageSize)
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 更新用户状态 0 - 禁用 1 - 启用
   * @param {*} id
   * @param {*} status
   * @returns
   */
  async updateStatus (id, status) {
    if (!['0', '1'].includes(status)) {
      return {
        errorMessage: '非法的status值'
      }
    }
    try {
      const exist = await userModel.exist(id)
      if (!exist) {
        return {
          errorMessage: '用户不存在'
        }
      }
      await userModel.updateStatus(id, status)
    } catch (error) {
      throw new Error(error)
    }
  }

  async updateInfo (id, attr) {
    try {
      const exist = await userModel.exist(id)
      if (!exist) {
        return {
          errorMessage: '用户不存在'
        }
      }
      await userModel.update(id, attr)
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new UserService()
